package com.heshan.test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;

/**
 * Created by lanouhn on 17/7/18.
// */
//从网站上下载一张图片，然后保存到本地计算机桌面上
public class ImageDownload {
    public static void main(String [] args) throws MalformedURLException {
        //设置网络连接变量
        HttpURLConnection connection = null;
        //设置接受流对象
        String ImgUrl="http://tse1.mm.bing.net/th?id=OIP.Xgmqp4_IgDzMxRzBHuvMEQEgDY&w=271&h=193&c=7&qlt=90&o=4&pid=1.7";
        URL url = new URL(ImgUrl);
        try {
            connection = (HttpURLConnection) url.openConnection();
            int code = connection.getResponseCode();
            if (code==200){
                System.out.println("打开成功");
                BufferedImage img = ImageIO.read(connection.getInputStream());

                String path = "/Users/lanouhn/Desktop/heshan.jpg";
                File fl = new File(path);
                ImageIO.write(img,"jpg",fl);

            }
            else{
                System.out.println("打开失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (connection !=null){
                connection.disconnect();
            }
        }

    }
}
